<template>
  <div>
    <div class="example">
      excel导入组件（.xls,.xlsx的文件）（需要手动定义展示页表头字段，以方便后端对接）
      <el-upload
        class="upload"
        action
        :multiple="false"
        :show-file-list="false"
        accept="application/vnd.openxmlformats-
        officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
        :http-request="httpRequest"
      >
        <el-button size="small" type="primary">批量导入</el-button>
      </el-upload>
    </div>
    <eltable
      :tablelist="tablelist"
      :tableData="formData"
      :changeedit="false"
    ></eltable>
  </div>
</template>

<script lang="ts">
import XLSX from "xlsx";
import eltable from "@/components/eltable/eltable.vue";
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
@Component({
  components: {
    eltable
  }
})
export default class extends Vue {
  @Prop({}) theader!: string[]; // 传过来的表头
  public formData: any = []; // 存放生成的数据
  public tablelist: any = []; // 展示页面的表头

  private httpRequest(e: any) {
    const { file } = e; // 文件信息
    if (!file) {
      // 没有文件
      return false;
    }
    if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
      // 格式根据自己需求定义
      this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
      return false;
    }

    const fileReader = new FileReader();
    // eslint-disable-next-line consistent-return
    fileReader.onload = (ev: any) => {
      const data = ev.target.result;
      const workbook = XLSX.read(data, {
        type: "binary" // 以字符编码的方式解析
      });
      const exlname = workbook.SheetNames[0]; // 取第一张表
      const exl: any = XLSX.utils.sheet_to_json(workbook.Sheets[exlname]); // 生成json表格内容
      this.formData = [];
      const theader = Object.keys(exl[0]); // excel的原始表头数据
      // 要求使用者必须传入展示栏头部数据
      if (!this.theader) {
        return this.$message.error("请传入表头数据");
      }
      const header = this.theader;
      // 生成展示数据（formData）
      exl.forEach((v: any) => {
        const obj: any = {};
        header.forEach((s: any, j: number) => {
          obj[header[j]] = v[theader[j]];
        });
        this.formData.push(obj);
      });
      console.log(this.formData);
      // 生成展示表头数据（tablelist）
      theader.forEach((v, i) => {
        const obj: any = {};
        obj.prop = this.theader[i];
        obj.label = v;
        obj.type = "text";
        this.tablelist.push(obj);
      });
    };
    fileReader.readAsBinaryString(file);
  }

  // @Watch("formData")
  // private watchTheader(n: any, o: any) {
  //   this.tablelist = [{ prop: "first", label: "" }];
  // }
}
</script>

<style></style>
